import { create } from 'zustand'
import { GPTDataItem } from '@/types/chat'

type State = {
  chatList: GPTDataItem[]
}

type Action = {
  setChatList: (list: GPTDataItem[]) => void
  addSendMsg: (msg: GPTDataItem) => void
  addReceiveMsg: (msg: GPTDataItem) => void
}
const replaceThink = (str: string) => {
  try {
    return str
      .replace(/<think[^>]*>/gi, '\n:::think\n')
      .replace(/<\/think>/gi, '\n:::\n')
  } catch (error) {
    console.error('Error replacing think:', error)
    return str
  }
}
const useChatStore = create<State & Action>((set, get) => ({
  chatList: [],
  setChatList: (list) => set({ chatList: list }),
  addSendMsg: (msg) =>
    set((state) => ({
      chatList: [...state.chatList, msg],
    })),
  addReceiveMsg: (msg) => {
    const prevList = get().chatList
    const lastMsg = prevList[prevList.length - 1]

    let newList: GPTDataItem[]
    if (lastMsg?.sender_type === 'gpt') {
      // 合并最后一条 GPT 消息
      const updatedMsg = {
        ...lastMsg,
        message: lastMsg.message + msg.message,
      }
      newList = [...prevList.slice(0, -1), updatedMsg]
    } else {
      console.log('我走的新增', lastMsg)

      // 新增一条 GPT 消息
      newList = [...prevList, { ...msg, message: msg.message }]
    }

    set({ chatList: newList })
  },
}))

export default useChatStore
